package com.travel.ticket.web;

import com.alibaba.fastjson.JSON;
import com.travel.common.vo.MemberRespVo;
import com.travel.ticket.service.CollectionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

import static com.travel.common.constant.AuthServerConstant.LOGIN_USER;

@Controller
public class CollectionWebController {

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    CollectionService collectionService;

    @GetMapping("/saveCollection")
    public String saveCollection(@RequestParam("spuId")Integer spuId){
        //1. 从redis中取出用户信息
        String s = redisTemplate.opsForValue().get(LOGIN_USER);
        MemberRespVo memberRespVo = JSON.parseObject(s,MemberRespVo.class);
        Integer userId = memberRespVo.getMemberId().intValue();

        //2. 判断是否收藏过
        Boolean collection = collectionService.isCollection(spuId, userId);

        //3.1 没收藏，保存
        if(!collection){
            collectionService.saveCollection(spuId,userId);
        }else{
            //3.2 收藏过，删除
            collectionService.deleteCollection(spuId,userId);
        }

        //http://sight.travel.com/43.html
        return "redirect:http://ticket.travel.com/"+spuId+".html";
    }
}
